package com.haibo.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author : 刘海波
 * @Date: 2025-08-28 23:14
 * @Description:
 * 原理：
 *      1、@MappedJdbcTypes(JdbcType.VARCHAR)：指定要处理的数据类型是varchar
 *      2、@MappedTypes(List.class)：指定要处理的Java类型是List类型
 *      3、这两个注解结合起来就可以锁定要处理的字段是List类型的famousUniversities了
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class List2VarcharTypeHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        StringBuffer sb = new StringBuffer();
        for (String param : parameter) {
            sb.append(param).append(",");
        }
        String value = sb.toString().substring(0,sb.toString().lastIndexOf(","));
        ps.setString(i,value);
    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (StringUtils.isNotBlank(value)) {
            return Arrays.asList(value.split(","));
        }
        return null;
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (StringUtils.isNotBlank(value)) {
            return Arrays.asList(value.split(","));
        }
        return null;
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (StringUtils.isNotBlank(value)) {
            return Arrays.asList(value.split(","));
        }
        return null;
    }


}
